package com.erp.produce.service.impl;

import com.alibaba.fastjson.JSON;
import com.erp.common.ResponseMessage;
import com.erp.common.util.ServiceUtil;
import com.erp.common.util.StringUtil;
import com.erp.common.util.TimeUtil;
import com.erp.produce.dao.OrderDao;
import com.erp.produce.dao.ProductionTaskDao;
import com.erp.produce.dao.ProductionTechnologyDao;
import com.erp.produce.dto.GoodsInfo;
import com.erp.produce.dto.ProductionTechnologyDTO;
import com.erp.produce.entity.Order;
import com.erp.produce.entity.ProductionTask;
import com.erp.produce.service.OrderService;
import com.erp.produce.service.ProductionTaskService;
import com.erp.stock.dao.CooperativesRawMaterialInventoryDao;
import com.erp.stock.dao.RawMaterialDao;
import com.erp.stock.dao.RawMaterialInventoryDao;
import com.erp.stock.entity.CooperativesRawMaterialInventory;
import com.erp.stock.entity.RawMaterial;
import com.erp.stock.entity.RawMaterialInventory;
import lombok.extern.slf4j.Slf4j;
import org.reflections.vfs.Vfs;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class ProductionTaskServiceImpl implements ProductionTaskService {
    @Autowired
    ProductionTaskDao dao;

    @Autowired
    CooperativesRawMaterialInventoryDao cooperativesRawMaterialInventoryDao;

    @Autowired
    OrderService orderService;

    @Autowired
    OrderDao orderDao;

    @Autowired
    ProductionTechnologyDao ptDao;

    @Autowired
    RawMaterialInventoryDao rawMaterialInventoryDao;

    @Autowired
    RawMaterialDao rawMaterialDao;
    @Override
    public Boolean update(ProductionTask productionTask) {
        ProductionTask productionTask1 = dao.findById(productionTask.getId()).get();
        BeanUtils.copyProperties(productionTask,productionTask1);
        return dao.saveAndFlush(productionTask1) != null;
    }

    @Override
    public Boolean add(ProductionTask productionTask) {
        productionTask.setCreateTime(TimeUtil.now());
        return dao.save(productionTask) != null;
    }

    @Override
    public Boolean deleteIds(Long[] ids) {
        return ServiceUtil.deleteIds(ids,dao);
    }

    @Override
    public List<ProductionTask> listPage(int page, int size) {
        return dao.findAll(PageRequest.of(page, size,
                new Sort(Sort.Direction.ASC,"orderId"))).getContent();
    }

    @Override
    public List<ProductionTask> listPageLike(int page, int size, String column) {
        return dao.findAllByCooperativesNameLike(PageRequest.of(page, size,new Sort(Sort.Direction.ASC,"id")), StringUtil.addLike(column));
    }


    @Override
    @Transactional
    public Boolean saveTasks(List<ProductionTask> tasks) {
        //
        for (ProductionTask task:tasks) {
            Long orderId = task.getOrderId();
            Order order = orderDao.findById(orderId).get();
            //根据表中产品及对应生产工艺计算出所需原材料的库存
            String orderInfoStr = order.getGoodInfo();
            List<GoodsInfo> goodsInfos = JSON.parseArray(orderInfoStr, GoodsInfo.class);
            goodsInfos.forEach(goodsInfo -> {

                String tempPT = goodsInfo.getPt();

                String technology = ptDao.findFirstByName(tempPT).getTechnology();
                List<ProductionTechnologyDTO> ptList = JSON.parseArray(technology, ProductionTechnologyDTO.class);
                for (ProductionTechnologyDTO pt : ptList) {
                    //访问原材料库存 减去库存
                    System.out.println(pt);
                    //获取当前原材料库存
                    RawMaterialInventory rmInventory = rawMaterialInventoryDao.findFirstByRawMaterialId(pt.getRM().getId());
                    //获取当前原材料信息
                    RawMaterial currentRawMaterial = rawMaterialDao.findById(pt.getRM().getId()).get();
                    //CooperativesRawMaterialInventory cooperativesRawMaterialInventory = cooperativesRawMaterialInventoryDao.findFirstByCooperativesName(task.getCooperativesName());
                    //新建外协企业原材料
                    CooperativesRawMaterialInventory cooperativesRawMaterialInventory1 = new CooperativesRawMaterialInventory();
                    //为外协企业原材料库存设置信息
                    cooperativesRawMaterialInventory1.setCooperativesName(task.getCooperativesName());
                    cooperativesRawMaterialInventory1.setRawMaterialId(currentRawMaterial.getId());
                    cooperativesRawMaterialInventory1.setRawMaterialName(currentRawMaterial.getName());
                    cooperativesRawMaterialInventory1.setOrderId(task.getOrderId());



                    if (goodsInfo.getGoodsUnit().trim().equals("千克")) {
                        //计算单位为公斤时的消耗当前原材料的量
                        Double reduceCurrentRm = (1 + task.getRaisePercent() / 100) * goodsInfo.getGoodsNumber() * pt.getRMPercent() / 100;
                        rmInventory.setCount(rmInventory.getCount() - reduceCurrentRm);
                        rawMaterialInventoryDao.save(rmInventory);
                        cooperativesRawMaterialInventory1.setInventory(reduceCurrentRm);
                        cooperativesRawMaterialInventoryDao.save(cooperativesRawMaterialInventory1);
                        log.info("`````````````````````````````````````````kg");
                    } else {
                        log.info("`````````````````````````````````````````pi");
                        Double reduceCurrentRm = (1 + task.getRaisePercent() / 100) * goodsInfo.getGoodsNumber()*20* pt.getRMPercent()/100;
                        rmInventory.setCount(rmInventory.getCount() - reduceCurrentRm);
                        cooperativesRawMaterialInventory1.setInventory(reduceCurrentRm);
                        cooperativesRawMaterialInventoryDao.save(cooperativesRawMaterialInventory1);
                        rawMaterialInventoryDao.save(rmInventory);
                    }
                }
            });
            task.setRmSend(1);
            Boolean addSucess = this.update(task);
            if (!addSucess) {
                return false;
            }
        }
        orderService.changeStatus(4,tasks.get(0).getOrderId());
        return true;
    }

    @Override
    public List<ProductionTask> list(Long orderId) {
        return dao.findAllByOrderId(orderId);
    }
}
